from flask import Flask, request, send_file, render_template,jsonify
import os
import re
import io
from PIL import Image
app = Flask(__name__)

def vlw_to_hex_with_separator(file_path):
    """
    将vlw文件转换为十六进制表示形式，并用0x和逗号作为分隔符
    """
    hex_data = []
    with open(file_path, 'rb') as file:
        byte_data = file.read()
        for byte in byte_data:
            hex_value = hex(byte)[2:].zfill(2).upper()
            hex_data.append(f"0x{hex_value}")
    return ",".join(hex_data)

def vlw_to_hex_with_separator(file_path):
    """
    将vlw文件转换为十六进制表示形式，并用0x和逗号作为分隔符
    """
    hex_data = []
    with open(file_path, 'rb') as file:
        byte_data = file.read()
        for byte in byte_data:
            hex_value = hex(byte)[2:].zfill(2).upper()
            hex_data.append(f"0x{hex_value}")
    return ",".join(hex_data)

def convert_to_camel_case(chinese_str):
    # 定义一个中文字符串
    chinese_str = chinese_str

    # 用于存储转换后的Unicode表示形式的列表
    unicode_result = []
    for char in chinese_str:
        unicode_value = ord(char)
        # 获取十六进制形式的Unicode码点并去掉开头的0x，添加\u前缀
        unicode_char = "\\u{:04X}".format(unicode_value)
        unicode_result.append(unicode_char)

    # 将列表中的元素拼接成一个字符串
    final_unicode_str = "".join(unicode_result)
    # 使用正则表达式进行替换
    new_str = re.sub(r"\\u([0-9A-Fa-f]{4})", lambda x: "0x{}".format(x.group(1).upper()), final_unicode_str)
    result_str = ",".join([f"0x{code}" for code in new_str.split("0x")[1:]])
    return result_str


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload_file():
    # 检查是否有文件上传
    if 'file' not in request.files:
        return "没有文件", 400

    file = request.files['file']
    if file.filename == '':
        return "未选择文件", 400

    # 保存上传的文件
    upload_folder = "uploads"
    if not os.path.exists(upload_folder):
        os.makedirs(upload_folder)

    file_path = os.path.join(upload_folder, file.filename)
    file.save(file_path)

    # 将上传的vlw文件转换为十六进制并生成qingning_Font.h
    hex_data = vlw_to_hex_with_separator(file_path)

    # 生成并写入qingning_Font.h文件
    header_file_content = f"""#include <pgmspace.h>
const uint8_t qingning_Font[] PROGMEM = {{{hex_data}}};
"""
   

    # 直接返回生成的文件供下载
    return jsonify({"success": True, "data": header_file_content})

@app.route('/convert', methods=['POST'])
def convert_text():
   
    chinese_text = request.json.get('chinese_text')
    print(chinese_text)
    if not chinese_text:
        return "请输入中文文本", 400
    
    unicode_result = convert_to_camel_case(chinese_text)
    print(unicode_result)
    return jsonify({"success": True, "unicode_result": unicode_result})


# 获取图片rgb565部分
def to_hex(value, length=2):
    """将数值转换为带前导零的十六进制表示"""
    return hex(value)[2:].upper().zfill(length)

def convert_to_565(r, g, b):
    """将 RGB 转换为 16 位 Color565 格式"""
    return ((r & 0xf8) << 8) | ((g & 0xfc) << 3) | (b >> 3)

@app.route('/get_rgb565', methods=['GET','POST'])
def image_to_color565():
    if request.method == 'GET':
        return render_template('get_rgb565.html')
    """将上传的图片转换为 Color565 格式的 C 代码数组"""
    if 'image' not in request.files:
        return jsonify({"error": "No image file uploaded"}), 400

    file = request.files['image']
    
    try:
        # 读取图片
        img = Image.open(file)
        img = img.convert("RGB")
        width, height = img.size
        pixels = img.load()

        logs = []
        
        # 生成新的日志代码
        logs.append("""#include <Arduino.h> 
#include <TFT_eSPI.h>

#include "qingning_Img.h"//这里改为你图片库文件名称

TFT_eSPI tft;


void setup()
{
    //tft.init();
    tft.begin();
    tft.writecommand(0x36);
    tft.writedata(0x00); 

    //青柠博客：https://www.qingningz.cn/出品
    tft.fillScreen(TFT_WHITE);
    tft.setSwapBytes(true);
    tft.pushImage(0, 0, img1_width, img1_height, qingning_Img); //img1_width, img1_height是你图片的宽和高,会自动获取，无需修改 
  
}

void loop()
{

}

""")

        # 构建 C 语言代码
        output = f"// 图片尺寸: {width}x{height} px\n"
        output += f"// 大小: {(width * height * 2):,} Bytes\n\n"
        output += f"// 青柠博客：https://www.qingningz.cn/\n\n"
        output += "#include <pgmspace.h>\n\n"
        output += f"const int img1_width={width};\n"
        output += f"const int img1_height={height};\n\n"
        output += "const unsigned short qingning_Img[] PROGMEM = {\n"

        line = ''
        pixel_count = 0

        # 遍历每个像素并转换为 Color565
        for y in range(height):
            for x in range(width):
                r, g, b = pixels[x, y]
                pixel_value = convert_to_565(r, g, b)
                line += f"0x{to_hex(pixel_value, 4)}, "
                pixel_count += 1

                # 每行输出最多 16 个像素
                if pixel_count == 16:
                    output += line + '\n'
                    line = ''
                    pixel_count = 0

        # 处理最后一行（如果有的话）
        if line:
            output += line + '\n'

        output += '};\n'

        

        return jsonify({
            "logs": "\n".join(logs),
            "c_code": output
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500



if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0')
